/**
 * 
 */
package io.gitee.falllee.dao.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import io.gitee.falllee.dao.annotation.DaoConfig;
import io.gitee.falllee.dao.config.DaoConfigContextHolder;

/**
 * @author batty
 *
 */
@Aspect
@Component
@Order(99)
public class DaoConfigAspect {

    private static final String EXPR = "daoPointcut()";

    /**
     * 拦截@DaoConfig注解的方法
     */
    @Pointcut("@annotation(io.gitee.falllee.dao.annotation.DaoConfig)")
    private void daoPointcut() {
        // 定义拦截规则，无实现
    }

    @Before(EXPR)
    public void doBefore(JoinPoint point) {
        Method method = getMethod(point);
        DaoConfig daoConfig = method.getAnnotation(DaoConfig.class);
        // 设置DAO配置
        DaoConfigContextHolder.setDaoConfig(daoConfig.value());
        DaoConfigContextHolder.setIncludeDisable(daoConfig.includeDisable());
        DaoConfigContextHolder.setDisableCache(daoConfig.disableCache());
        DaoConfigContextHolder.setAddGlobalFilter(daoConfig.addGlobalFilter());
    }

    @After(EXPR)
    public void doAfter(JoinPoint point) {
        DaoConfigContextHolder.clearDaoConfig();
    }

    private Method getMethod(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        return signature.getMethod();
    }
}
